﻿using Microsoft.EntityFrameworkCore;
using 搭建EFCore开发环境;

namespace EFCore_增删改查
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            using (var db = new MyContext())
            {
                ////插入数据
                //Book book = new Book() { Price = 39, PubTime = DateTime.Now, Title = "Asp.NetCore" };
                //db.Books.Add(book);
                //await db.SaveChangesAsync();


                ////批量插入
                //List<Book> books = new List<Book>()
                //{
                //    new Book(){Price=50,PubTime=new DateTime(2025,1,3),Title="WPF"},
                //    new Book(){Price=60,PubTime=new DateTime(2010,10,9),Title="WPF"},
                //    new Book(){Price=70,PubTime=new DateTime(2020,1,3),Title="Java"},
                //};

                //await db.Books.AddRangeAsync(books);
                //await db.SaveChangesAsync();



                //查询
                //var books = db.Books.Where(e => e.Price >= 60);
                //foreach (var book in books)
                //{
                //    Console.WriteLine($"Id={book.Id}\tTitle={book.Title}\tPrice={book.Price}");
                //}

                //var book = db.Books.Where(e => e.Id > 100).FirstOrDefault();    //如果改成Fisrt()，则会报错
                //Console.WriteLine(book?.Id);


                ////删除
                ////如果删除的对象不存在，则会报错
                //Book book = db.Books.SingleOrDefault(e => e.Id == 7);

                ////以下两种写法都可以
                ////db.Books.Remove(book);
                //db.Remove(book);
                //db.SaveChanges();

                //修改
                //Book book = db.Books.Single(e => e.Id == 8);
                //book.Price = 100;
                //db.SaveChangesAsync();

                ////批量删除
                //db.Books.Where(e => e.Price < 100).ExecuteDelete();

                //批量修改
                await db.Books.Where(e => e.Price > 60).ExecuteUpdateAsync(
                    e => e.SetProperty(x => x.Price, x => x.Price + 50)
                    .SetProperty(x => x.PubTime, x => new DateTime(2000, 1, 1))
                    );

            }
        }
    }
}
